# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 22:10:55 2019
@author: shael
Tesing Pycharm Git
"""

import mysql.connector
import numpy as np
from mysql.connector import Error
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from plotly.offline import plot
from scipy.optimize import curve_fit
import datetime
from sympy import Eq, var, solve,nsolve,Symbol,nonlinsolve
#from plotly.graph_objs import Layout
import sympy
from scipy import integrate,optimize

def func(X, a, b, c,d,e,f):
    #return a * np.exp(-b * x) - c
    x,y=X
    return (((d*(y**e)))/x*f)+(a * np.exp(-b * x) + c)
    #return a *x**b
    #return a*((x)/(x+b))
    
def findUnknowns(im,trace,poptop): #impendance, trace,equatio parameters
    if(im>100):
        return 5,5  
    a=poptop[0]
    b=poptop[1]
    c=poptop[2]
    d=poptop[3]
    e=poptop[4]
    f=poptop[5]
    z=im
    x=Symbol("x")#length
    lengths=[4.1,4.35,4.6,4.85,3.6,3.1,2.6,2.1,1.6]
    for length in lengths:
        y=length
        lowerboundim = ((d * (y ** e))) / .5 * f + ((a * sympy.exp(-b * .5) + c)) # find lower bound width is .5
        upperboundim = ((d * (y ** e))) /  5 * f + ((a * sympy.exp(-b *  5) + c))  # find lower bound width is .5
        if(im>upperboundim or im<lowerboundim): # if its outside the bounds of the function dont try and curvfit
            continue# check next length
        #q=(a * np.exp(-b * x) + c)-z'
        try:
            width=nsolve(((d*(y**e)))/x*f+((a * sympy.exp(-b * x) + c)-z),x,.01)
            if(width<5):
                return width,length
        except Error as e:
            print(e)
        print(width)
        print(length)
        print(" ")
    # max for both if too high
    return 5,5


    
        

def curveFit(substrateMat):
    try:
        mydb=mysql.connector.connect(
                 
                host="bmckean.dynu.net",
                user="msurf-script",
                passwd="Capstone#2019",
                database="metasurface_design"
        
                )
        mycursor=mydb.cursor()
        print(mydb.is_connected())
    except Error as e:
        print(e)
    try:
                query="SELECT * from dogbone_simulations;" 
                mycursor.execute(query)
                results=mycursor.fetchall()
                mydb.commit()
                tab_name="dogbone_simulations"
                query="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = \"%s\";" %(tab_name) 
                mycursor.execute(query)
                colsqur=mycursor.fetchall()
                cols=[]
                for col in colsqur:
                    col=str(col[0])
                    cols.append(col)
                mydb.commit()
    except Error as e:
                print("Error reading data from MySQL table", e)
    df1=pd.DataFrame(results)
    df1.columns=cols
    df1 = df1[df1['length'] != 1.1]
    if(substrateMat=='Rogers RO3003'):
        df1 = df1[df1['length'] != 1.1]
        df1 = df1[df1['length'] != 1.6]
    if (substrateMat == 'Rogers RO3010'):
        df1 = df1[df1['length'] != 1.35]
        df1 = df1[df1['length'] != 1.6]

    df1=df1[df1['substrate_material'] == substrateMat]
    
    
    mergedResults= df1
    
    mergedResults.to_pickle("IMPEDANCE_backup_%s")
    
    topsdf=mergedResults.loc[mergedResults['location']=='top'].sort_values(['width'])
    midsdf=mergedResults.loc[mergedResults['location']=='mid'].sort_values(['width'])
    botsdf=mergedResults.loc[mergedResults['location']=='bot'].sort_values(['width'])
    
    poptop, pcovtop = curve_fit(func, (topsdf['width'],topsdf['length']),topsdf['z'] ,bounds=([-25000,-1500,-1500,-100000,-10,-10], [25000, 1500, 1500,25000,10,10]))
    popmid, pcovmid = curve_fit(func, (midsdf['width'],midsdf['length']),midsdf['z'] ,bounds=([-25000,-1500,-1500,-100000,-10,-10], [25000, 1500, 1500,25000,10,10]))
    popbot, pcovbot = curve_fit(func, (botsdf['width'],botsdf['length']),botsdf['z'] ,bounds=([-25000,-1500,-1500,-100000,-10,-10], [25000, 1500, 1500,25000,10,10]))

    
    #findUnknowns(-100,'top',poptop)
    

    
    fig = make_subplots(rows=1, cols=1,
                        subplot_titles=("Top_Trace","Mid_Trace","Bot_Trace"),
                        specs=[[{"type":"scene"}]])
    
  
    fig.update_layout(height=1000, width=1000, title_text="Width of Dogbone v Impedance",paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,1)')
    fig.append_trace(go.Scatter3d(
        x=topsdf['width'],
        y=topsdf['length'],
        z=topsdf['z'],
        name="Simulation Data",
    ), row=1, col=1)
    
    
    fig.append_trace(go.Scatter3d(
        x=topsdf['width'],
        y=topsdf['length'],
        z=func((topsdf['width'],topsdf['length']),*poptop),
        name="Curve Fitting Points"
    ), row=1, col=1)
#    
#    fig.append_trace(go.Scatter3d(
#        x=midsdf['width'],
#        y=midsdf['z'],
#        name="Mid Data"
#    ), row=2, col=1)
##    
##    fig.append_trace(go.Scatter3d(
##        x=midsdf['width'],
##        y=func(midsdf['width'],*popmid),
##        name="Mid Curve"
##    ), row=2, col=1)
##    
#    fig.append_trace(go.Scatter3d(
#        x=botsdf['width'],
#        y=botsdf['z'],
#        name="Bot Data"
#    ), row=3, col=1)
    
#    
#    fig.append_trace(go.Scatter3d(
#        x=botsdf['width'],
#        y=func(botsdf['width'],*popbot),
#        name="Bot Curve"
#    ), row=3, col=1)
    fig.update_layout(scene = dict(
                    xaxis_title='Width(mm)',
                    yaxis_title='Length(mm)',
                    zaxis_title='Impedance'),
                    width=1000,
                    margin=dict(r=20, b=10, l=10, t=10),
                   paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,1)' )
  
    #fig.update_layout(layout=layout)
    plot(fig)
   # return fig
    return poptop,popmid,popbot 




    


    
    